package com.nanyang.tms.controller.handler;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.jackson.JsonComponent;
import org.springframework.web.util.HtmlUtils;

import java.io.IOException;

@JsonComponent

public class CustomObjectMapper {
	 private static String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"  
	            + "(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)";
	public static class Serializer extends JsonSerializer<String> {
		@Override
		public void serialize(String value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
			 if (value != null) {
	                String encodedValue =value;
	                jsonGenerator.writeString(HtmlUtils.htmlUnescape(encodedValue));
	            }
		}
	}

	public static class Deserializer extends JsonDeserializer<String> {
		@Override
		public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
			String value = jsonParser.getValueAsString();
	            if (value != null) {
	                return HtmlUtils.htmlEscape(value.toString().replaceAll(reg, ""));
	            }
	            return value;
		}
	}
}
